<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="modalTitle" @ok="onButtonOkClick">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts">
  import { defineComponent, ref, unref, inject, onMounted } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';

  import { pointsFormSchema } from './points.data';
  import { addPoints, updatePoints, getPoints } from '/@/api/demo/timeseries';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';

  import { queryEnumOptions } from '/@/api/platform/enum';

  const { createMessage } = useMessage();
  export default defineComponent({
    name: 'AddOrUpdatePoints',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      // 操作类型
      const op = ref(OperationTypeEnum.UN_KNOWN);
      // 数据ID
      const dataId = ref('');
      // 标题
      const modalTitle = ref('时序点号');

      const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
        labelWidth: 80,
        schemas: pointsFormSchema, // 需要您定义这个schema
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      /**
       * 处理父组件传递的参数
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        // 接收父组件传递的数据
        if (data?.op) {
          op.value = data.op;
        }

        if (data?.dataId) {
          dataId.value = data.dataId;
        }

        // 根据操作类型设置标题
        if (op.value != OperationTypeEnum.UN_KNOWN && op.value != OperationTypeEnum.CUSTOME) {
          modalTitle.value = '时序点号--' + op.value;
        }

        resetFields(); // 重置表单
        setModalProps({ confirmLoading: false });

        //获取点号时段类型枚举，对表单中的时段类型待选项进行赋值
        queryEnumOptions('TimeRangeLengthEnum').then((res) => {
          let enumOptions = res[0].options.map((item) => {
            return {
              label: item.value,
              value: item.key,
            };
          });

          console.log('enumOptions', enumOptions);
          updateSchema([
            {
              field: 'tmtype',
              componentProps: {
                options: enumOptions,
              },
            },
          ]);
        });

        // 编辑模式加载数据
        if (op.value == OperationTypeEnum.EDIT) {
          getPointById();
          // 编辑时禁用关键字段
          updateSchema({ field: 'pointid', componentProps: { disabled: true } });
        } else {
          // 新增时启用所有字段
          updateSchema({ field: 'pointid', componentProps: { disabled: false } });
        }
      });

      /**
       * 获取点号详情
       */
      async function getPointById() {
        getPoints(dataId.value)
          .then((res) => {
            console.log('res=================>', res);
            setFieldsValue({
              ...res[0],
            });
            //编辑时设置时段类型选中；由于点号信息中的时段类型为number类型，待选项中的为string类型无法自动选中
            let pointTmType: String = res[0].tmtype.toString();
            setFieldsValue({ tmtype: pointTmType });
          })
          .catch((ex) => {
            console.log('catch', ex);
            createMessage.error(ex.msg);
          });
      }
      /**
       * 保存数据
       */
      async function onButtonOkClick() {
        if (op.value == OperationTypeEnum.ADD) {
          try {
            const values = await validate();
            setModalProps({ confirmLoading: true });
            addPoints(values)
              .then((res) => {
                if (!res || Object.keys(res).length == 0) {
                  createMessage.success('保存成功', 2);
                }
                opSuccess();
              })
              .catch((ex) => {
                console.log('catch ', ex);
                createMessage.error(ex.msg);
              });
          } finally {
            setModalProps({ confirmLoading: false });
          }
        } else if (op.value == OperationTypeEnum.EDIT) {
          const values = await validate();
          setModalProps({ confirmLoading: true });

          updatePoints(values) // 需要实现
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('修改成功', 2);
              }
              opSuccess();
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        } else {
          createMessage.error('当前操作类型错误，无法进行对应操作', 5);
        }
      }
      //操作成功后
      function opSuccess() {
        closeModal();
        emit('success');
      }

      onMounted(() => {});

      return {
        op,
        modalTitle,
        registerModal,
        registerForm,
        onButtonOkClick,
        getPointById,
        opSuccess,
      };
    },
  });
</script>

<style scoped lang="less"></style>
